๋ฌธ์
Programmers - ๋งค์นญ ์ ์
๐ Logic
for (String page : pages) {
Page p = new Page(word, page);
// url์ ํค๋ก ํ์ฌ ๋งต ์ถ๊ฐ
pageInfo.put(p.url, p);
}
Page ํด๋์ค์ setScore(), setExtPages() , setLinkScore() ๋ก ๊ฐ page ์ ๋ํด ๊ธฐ๋ณธ ์ ์์ ์ธ๋ถ ๋งํฌ ์, ๋งํฌ ์ ์๋ฅผ ๊ณ์ฐํ๋ค.
for (Page p : pageInfo.values()) {
for (String extPage : p.extPages) {
if (pageInfo.containsKey(extPage))
pageInfo.get(extPage).addScore(p.getLinkScore());
}
}
- ํด๋น ์น ํ์ด์ง๋ก ๋งํฌ๊ฐ ๊ฑธ๋ฆฐ ๋ค๋ฅธ ์น ํ์ด์ง์ ๋งํฌ ์ ์(๊ธฐ๋ณธ ์ ์ / ์ธ๋ถ ๋งํฌ ์)์ ์ดํฉ์ ๊ตฌํด ํด๋น ์น ํ์ด์ง์ ๋งค์นญ ์ ์๋ฅผ ๊ณ์ฐํ๋ค.
๐ CODE
์ฝ๋ ๋ณด๊ธฐ/์ ๊ธฐ๐ซ
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Page {
String url;
double score = 0;
double linkScore = 0;
ArrayList<String> extPages;
public Page(String word, String page) {
this.url = getUrl(page);
extPages = new ArrayList<>();
setScore(page, word);
setExtPages(page);
setLinkScore();
}
private String getUrl(String page) {
Pattern pattern = Pattern.compile("<meta property=\"og:url\" content=\"(\\S*)\"");
Matcher matcher = pattern.matcher(page);
if (matcher.find())
return matcher.group().split("=")[2].replaceAll("\"", "");
return "";
}
public void addScore(double score) {
this.score += score;
}
public double getScore() {
return score;
}
private void setScore(String page, String word) {
// body ํ๊ทธ ๋ด ๋ชจ๋ ์ซ์๋ค์ ๊ณต๋ฐฑ์ผ๋ก replaceํ์ฌ, word๋ฅผ ์ฐพ๊ธฐ ์ฝ๋๋ก ํจ
String body = page.split("<body>")[1].split("</body>")[0].replaceAll("\\d", " ");
Pattern pattern = Pattern.compile("\\b(?i)" + word + "\\b");
Matcher matcher = pattern.matcher(body);
while(matcher.find())
score++;
}
private void setExtPages(String page) {
Pattern pattern = Pattern.compile("<a href=\"https://(\\S*)\"");
Matcher matcher = pattern.matcher(page);
while(matcher.find())
extPages.add(matcher.group().split("\"")[1]);
}
public double getLinkScore() {
return linkScore;
}5
private void setLinkScore() {
this.linkScore = this.score / extPages.size();
}
}
class Solution {
public int solution(String word, String[] pages) {
word = word.toLowerCase();
Map<String, Page> pageInfo = new LinkedHashMap<>();
for (String page : pages) {
Page p = new Page(word, page);
// url์ ํค๋ก ํ์ฌ ๋งต ์ถ๊ฐ
pageInfo.put(p.url, p);
}
for (Page p : pageInfo.values()) {
for (String extPage : p.extPages) {
if (pageInfo.containsKey(extPage))
pageInfo.get(extPage).addScore(p.getLinkScore());
}
}
double maxScore = 0;
int maxIdx = 0;
int idx = 0;
for (Map.Entry<String, Page> entry : pageInfo.entrySet()) {
double score = entry.getValue().getScore();
if (score > maxScore) {
maxScore = score;
maxIdx = idx;
}
idx++;
}
return maxIdx;
}
}
โ๏ธ Review
- ๋ฌธ์ ์์ฒด๋ ๋งค์ฐ ๊ฐ๋จํ์ง๋ง ๊ตฌํ์ด ์ง์ง ๋๋ฌ์ ๋ ๋ฌธ์ ... ์ ๊ท ํํ์์ ์ ๋๋ก ์ดํดํ์ง ์์ผ๋ฉด ์ ๋ ๊ทธ๋ฅ ๋ชป ํ ๋ฏ ํ๋ค..
- ๋ฌธ์ ์ดํด๋ฅผ ์๋ชปํด์, ํด๋น ์น ํ์ด์ง๋ก ๋งํฌ๊ฐ ๊ฑธ๋ฆฐ ๋ค๋ฅธ ์นํ์ด์ง์ ๊ธฐ๋ณธ ์ ์ / ์ธ๋ถ ๋งํฌ์ ์์ ์ดํฉ์ ํด๋น ์น ํ์ด์ง๋ก ๋งํฌ๊ฐ ๊ฑธ๋ฆฐ ๋ค๋ฅธ ์น ํ์ด์ง์ ๊ธฐ๋ณธ ์ ์์ ํ์ฌ ํ์ด์ง์ ๋งํฌ์ ์์ ๋ํ ๊ณ์ฐ์ผ๋ก ์ฐฉ๊ฐํด์ ์๊ฐ์ ๋ ๋ ๋ ธ๋ค.